import {
  message,
  Modal,
  Space,
  Form,
  Input,
  Switch,
  Button,
  Upload,
  UploadProps,
  Image
} from 'antd';
import { DeleteOutlined,  UploadOutlined } from '@ant-design/icons';
import React, { PropsWithChildren, useEffect, useState } from 'react';
import { Banner } from '..';
import { addApi, selectOneApi, updateApi } from '../services';

interface EditFormProps {
  id?: number;
  modalVisible: boolean;
  onCancel: () => void;
  onSuccess?: () => void;
}

const { TextArea } = Input;
const user = JSON.parse(localStorage.getItem('user') || '{}');

const EditForm: React.FC<PropsWithChildren<EditFormProps>> = (props) => {
  const initialValues: Banner = {
    title: '',
    comment: '',
    status: 1,
    imageUrl: "",
    linkUrl: ""
  };

  const { modalVisible, onCancel, id, onSuccess } = props;
  const [form] = Form.useForm<Banner>();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');

  const uploadProps: UploadProps = {
    name: 'file',
    action: 'http://localhost:3000/api/upload/image',
    headers: {
      authorizationtoken: user.token,
    },
    showUploadList: false,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
      }
      return isImage;
    },
    onChange(info) {
      if (info.file.status === 'done') {
        const { code, data } = info.file.response;
        if (code == 200) {
          message.success(`上传成功`);
          // 假设返回的数据结构为 { url: '图片地址' }
          const imageUrl = data.url;
          if (imageUrl) {
            form.setFieldsValue({ imageUrl });
            setImageUrl(imageUrl);
          }

        }


      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    maxCount: 1,
  };

  useEffect(() => {
    if (modalVisible) {
      if (id) {
        selectOne();
      } else {
        form.resetFields();
        setImageUrl("")
      }
    }
  }, [modalVisible, id]);

  const selectOne = async () => {
    setLoading(true);
    try {
      const res = await selectOneApi(id!);
      if (res.code === 200) {
        const data = {
          ...res.data,
          status: Boolean(res.data.status)
        };
        form.setFieldsValue(data);
        if (data.imageUrl) {
          setImageUrl(data.imageUrl)
        }
      }
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values: Banner) => {
    setLoading(true);
    try {
      const submitData = {
        ...values,
        status: Number(values.status),
        ...(id ? { id } : {})
      };

      const submitFun = id ? updateApi : addApi;
      const res = await submitFun(submitData);

      if (res.code === 200) {
        message.success('提交成功');
        onCancel();
        onSuccess?.();
      }
    } catch (error) {
      message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  return (
    <Modal
      title={id ? "编辑" : "新建"}
      width={600}
      open={modalVisible}
      onCancel={onCancel}
      footer={null}
      destroyOnClose
    >
      <Form
        form={form}
        {...formItemLayout}
        layout="horizontal"
        initialValues={initialValues}
        onFinish={handleSubmit}
      >
        <Form.Item name="id" label="ID" hidden>
          <Input disabled />
        </Form.Item>

        <Form.Item
          name="title"
          label="名称"
          rules={[{ required: true, message: '请输入名称' }]}
        >
          <Input placeholder="请输入名称" />
        </Form.Item>

        <Form.Item label="封面图片">
          {imageUrl &&
            <div style={{ position: 'relative', cursor: "pointer", display: "inline-block" }}>
              <Image
                src={imageUrl}
                alt="封面"
                style={{
                  width: '100%',
                  maxHeight: '300px',
                  objectFit: 'cover',
                  borderRadius: 4,
                }}
                preview={true}
              />
              <Button
                type="link"
                danger
                size="small"
                icon={<DeleteOutlined />}
                style={{ position: 'absolute', top: 8, right: 8 }}
                onClick={(e) => {
                  e.stopPropagation();
                  setImageUrl("")
                  form.setFieldsValue({ imageUrl: "" });
                }}
              >

              </Button>
            </div>}
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />} loading={loading}>
              上传封面
            </Button>

          </Upload>
          <Form.Item name="imageUrl" noStyle>
            <Input type="hidden" />
          </Form.Item>
        </Form.Item>
        <Form.Item
          name="linkUrl"
          label="链接地址"
        >
          <Input placeholder="请输入链接地址" />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          valuePropName="checked"
        >
          <Switch
            checkedChildren="开启"
            unCheckedChildren="关闭"
          />
        </Form.Item>

        <Form.Item
          name="comment"
          label="描述"
        >
          <TextArea placeholder="请输入描述" rows={4} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
          <Space>
            <Button onClick={onCancel}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              提交
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default EditForm;